# GoFilm 多阶段构建 Dockerfile

# ==================== 前端构建阶段 ====================
FROM node:18-alpine AS frontend-builder

WORKDIR /app/client

# 复制前端依赖文件
COPY client/package*.json ./

# 安装前端依赖
RUN npm ci --only=production

# 复制前端源码
COPY client/ ./

# 构建前端
RUN npm run build

# ==================== 后端构建阶段 ====================
FROM golang:1.20-alpine AS backend-builder

# 安装必要工具
RUN apk add --no-cache git ca-certificates tzdata

WORKDIR /app/server

# 复制Go模块文件
COPY server/go.mod server/go.sum ./

# 下载依赖
RUN go mod download

# 复制后端源码
COPY server/ ./

# 构建后端二进制文件
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o gofilm main.go

# ==================== 运行时阶段 ====================
FROM alpine:latest

# 安装运行时依赖
RUN apk --no-cache add \
    ca-certificates \
    tzdata \
    ffmpeg \
    && rm -rf /var/cache/apk/*

# 设置时区
ENV TZ=Asia/Shanghai

# 创建应用用户
RUN addgroup -g 1001 -S gofilm && \
    adduser -S gofilm -u 1001 -G gofilm

WORKDIR /app

# 从构建阶段复制文件
COPY --from=backend-builder /app/server/gofilm .
COPY --from=frontend-builder /app/client/dist ./static/web
COPY --from=backend-builder /app/server/static ./static

# 创建必要目录
RUN mkdir -p static/hls logs data && \
    chown -R gofilm:gofilm /app

# 切换到应用用户
USER gofilm

# 暴露端口
EXPOSE 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/config/basic || exit 1

# 启动应用
CMD ["./gofilm"]